//
//  LoginViewController.m
//  GiganticWhale
//
//  Created by GiganticWhale on 16/9/8.
//  Copyright © 2016年 Gigantic. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginRegisterViewControler.h"              // 忘记密码
#import "LoginThirdLoginView.h"
#import <SMS_SDK/SMSSDK.h>

static char loginKey;
@interface LoginViewController()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)UITableView *loginTableView;
@property (nonatomic,strong)NSArray *loginArr;
@property (nonatomic,strong)UITextField *userTextField;
@property (nonatomic,strong)UITextField *pwdTextField;
@property (nonatomic,strong)UIButton *senderButton;
@property (nonatomic,strong)UIButton *resetButton;              /**< 忘记密码*/
@property (nonatomic,strong)UIButton *normalButton;             /**< 随便逛逛*/
@property (nonatomic,strong)UIButton *mianzeButton;             /**< 免责按钮*/
@property (nonatomic,strong)LoginThirdLoginView *bottomView;
@property (nonatomic,strong)PDCountDownButton *cutDownButton;   /**< 倒计时按钮*/
@property (nonatomic,copy)NSString *tempNumber;
@end

@implementation LoginViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    [self pageSetting];
    [self arrayWithInit];
    [self createTableView];
    [self createBottomView];    
}

#pragma mark - pageSetting
-(void)pageSetting{
    self.barMainTitle = @"登录";

    __weak typeof(self)weakSelf = self;
    if (self != [self.navigationController.viewControllers firstObject]){
        [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"icon_main_back"] barHltImage:[UIImage imageNamed:@"icon_main_back"] action:^{
            if (!weakSelf){
                return ;
            }
            __strong typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf.navigationController popViewControllerAnimated:YES];
        }];
    } else {
        [self leftBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"icon_main_cancel"] barHltImage:[UIImage imageNamed:@"icon_main_cancel"] action:^{
            if (!weakSelf){
                return ;
            }
            __strong typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf.navigationController dismissViewControllerAnimated:YES completion:NULL];
        }];
    }
}

#pragma mark - arrayWithInit

-(void)arrayWithInit{
    self.loginArr = @[@[@"账号",@"密码"],@[@"协议"],@[@"登录"]];
}

-(void)createTableView{
    if (!self.loginTableView){
        self.loginTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        self.loginTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight |UIViewAutoresizingFlexibleWidth;
        [self.loginTableView setDelegate:self];
        [self.loginTableView setDataSource:self];
        [self.loginTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [self.loginTableView setBackgroundColor:[UIColor clearColor]];
        [self.loginTableView setTableFooterView:[[UIView alloc]initWithFrame:CGRectZero]];
        [[self view] addSubview:self.loginTableView];
    }
}

#pragma mark UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.loginArr.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *sectionOfArr = [self.loginArr objectAtIndex:section];
    return sectionOfArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellHeight = [tableView rectForRowAtIndexPath:indexPath].size.height;
    if (indexPath.section == 0){
        static NSString *cellIdentifyWithRowOne = @"cellIdentifyWithRowOne";
        UITableViewCell *cellWithRowOne = [tableView dequeueReusableCellWithIdentifier:cellIdentifyWithRowOne];
        if (!cellWithRowOne){
            cellWithRowOne = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifyWithRowOne];
            cellWithRowOne.selectionStyle = UITableViewCellSelectionStyleNone;
            cellWithRowOne.backgroundColor = [UIColor clearColor];
            // 1. inputTextField
            UITextField *inputTextField = [[UITextField alloc] init];
            inputTextField.frame = CGRectMake(LCFloat(11), 0, kScreenBounds.size.width - 2 * LCFloat(11), cellHeight);
            inputTextField.backgroundColor = [UIColor clearColor];
            inputTextField.font = [UIFont fontWithCustomerSizeName:@"正文"];
            inputTextField.delegate = self;
            inputTextField.stringTag = @"inputTextField";
            [cellWithRowOne addSubview:inputTextField];
            
            __weak typeof(self)weakSelf = self;
            PDCountDownButton *cutDownButton = [[PDCountDownButton alloc]initWithFrame:CGRectMake(kScreenBounds.size.width - LCFloat(100) - LCFloat(11), 0, LCFloat(100), cellHeight) daojishi:30 withBlock:^{
                if (!weakSelf){
                    return ;
                }
                __strong typeof(weakSelf)strongSelf = weakSelf;
                [strongSelf sendRequestToGetSmsCode];
            }];
            cutDownButton.stringTag = @"cutDownButton";
            [cellWithRowOne addSubview:cutDownButton];
        }
        UITextField *inputTextField = (UITextField *)[cellWithRowOne viewWithStringTag:@"inputTextField"];
        PDCountDownButton *cutDownButton = (PDCountDownButton *)[cellWithRowOne viewWithStringTag:@"cutDownButton"];
        if (indexPath.row == 0){                // 手机号
            inputTextField.keyboardType = UIKeyboardTypeNumberPad;
            self.userTextField = inputTextField;
            self.userTextField.placeholder = @"请输入手机号";
            self.userTextField.returnKeyType = UIReturnKeyContinue;
            cutDownButton.hidden = YES;
        } else if (indexPath.row == 1){
            inputTextField.keyboardType = UIKeyboardTypeNumberPad;
            self.pwdTextField = inputTextField;
            self.pwdTextField.placeholder = @"请输入验证码";
            self.pwdTextField.returnKeyType = UIReturnKeyDone;
//            self.pwdTextField.secureTextEntry = YES;
            cutDownButton.hidden = NO;
            self.cutDownButton = cutDownButton;
        }
        return cellWithRowOne;
    } else if (indexPath.section == 1){
        static NSString *cellIdentifyWithRowThr = @"cellIdentifyWithRowThr";
        UITableViewCell *cellWithRowThr = [tableView dequeueReusableCellWithIdentifier:cellIdentifyWithRowThr];
        if (!cellWithRowThr){
            cellWithRowThr = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifyWithRowThr];
            cellWithRowThr.selectionStyle = UITableViewCellSelectionStyleNone;
            cellWithRowThr.backgroundColor = [UIColor clearColor];
            // 1. 创建免责声明
            self.mianzeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            UIImage *checkNormal = [UIImage imageNamed:@"login_delegate_check_nor"];
            [self.mianzeButton setBackgroundImage:checkNormal forState:UIControlStateNormal];
            [self.mianzeButton setBackgroundImage:[UIImage imageNamed:@"login_delegate_check_hlt"] forState:UIControlStateSelected];
            __weak typeof(self)weaKSelf = self;
            [self.mianzeButton buttonWithBlock:^(UIButton *button) {
                if (!weaKSelf){
                    return ;
                }
                __strong typeof(weaKSelf)strongSelf = weaKSelf;
                [Tool clickZanWithView:strongSelf.mianzeButton block:^{
                    strongSelf.mianzeButton.selected = !self.mianzeButton.selected;
                }];
            }];
            self.mianzeButton.adjustsImageWhenHighlighted = NO;
            self.mianzeButton.selected = YES;
            [cellWithRowThr addSubview:self.mianzeButton];

            // 我已阅读
            UILabel *fixedLabel = [[UILabel alloc]init];
            fixedLabel.backgroundColor = [UIColor clearColor];
            fixedLabel.stringTag = @"fixedLabel";
            fixedLabel.font = [UIFont fontWithCustomerSizeName:@"小提示"];
            fixedLabel.textColor = [UIColor colorWithCustomerName:@"黑"];
            fixedLabel.text = @"我已阅读【炽热教育】用户合作协议";
            [cellWithRowThr addSubview:fixedLabel];
        }
        UILabel *fixedLabel = (UILabel *)[cellWithRowThr viewWithStringTag:@"fixedLabel"];
        CGSize contentOfSize = [fixedLabel.text sizeWithCalcFont:fixedLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, cellHeight)];
        CGFloat margin_x = (kScreenBounds.size.width - contentOfSize.width - LCFloat(11) - cellHeight) / 2.;
        self.mianzeButton.frame = CGRectMake(margin_x,(cellHeight - LCFloat(13)) / 2. , LCFloat(13), LCFloat(13));
        fixedLabel.frame = CGRectMake(CGRectGetMaxX(self.mianzeButton.frame) + LCFloat(11), 0, contentOfSize.width, cellHeight);
        
        return cellWithRowThr;
    } else if (indexPath.section == 2){
        static NSString *cellIdentifyWithRowTwo = @"cellIdentifyWithRowTwo";
        GWButtonTableViewCell *cellWithRowTwo = [tableView dequeueReusableCellWithIdentifier:cellIdentifyWithRowTwo];
        if (!cellWithRowTwo){
            cellWithRowTwo = [[GWButtonTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifyWithRowTwo];
        }
        cellWithRowTwo.transferCellHeight = cellHeight;
        [cellWithRowTwo setButtonStatus:NO];
        cellWithRowTwo.transferTitle = @"登录";
        __weak typeof(self)weakSelf = self;
        [cellWithRowTwo buttonClickManager:^{
            if (!weakSelf){
                return ;
            }
            __strong typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf yanzhengSmsCodeManager];
        }];
        return cellWithRowTwo;
    }
    return nil;
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        return LCFloat(20);
    } else if (indexPath.section == 2){
        return [GWButtonTableViewCell calculationCellHeight];
    } else {
        return 50;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0){
        return LCFloat(10);
    } else {
        return LCFloat(20);
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = [UIColor clearColor];
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1){
        return LCFloat(30);
    } else {
        return 0;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        PDWebViewController *webViewController = [[PDWebViewController alloc]init];
        [webViewController webViewControllerWithAddress: [AccountModel sharedAccountModel].login_delegate];
        [self.navigationController pushViewController:webViewController animated:YES];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]init];
    footerView.backgroundColor = [UIColor clearColor];
    
    // 1. 创建忘记密码
    
    self.resetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.resetButton.frame = CGRectMake(LCFloat(11), 0, 100, LCFloat(30));
    [self.resetButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [self.resetButton setTitleColor:[UIColor colorWithCustomerName:@"浅灰"] forState:UIControlStateNormal];
    [self.resetButton setTitleColor:[UIColor colorWithCustomerName:@"黑"] forState:UIControlStateHighlighted];
    self.resetButton.backgroundColor = [UIColor clearColor];
    __weak typeof(self)weakSelf = self;
    [self.resetButton buttonWithBlock:^(UIButton *button) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = self;
        LoginRegisterViewControler *registerViewController = [[LoginRegisterViewControler alloc]init];
        registerViewController.transferType = registerVCTypeReset;
        [strongSelf.navigationController pushViewController:registerViewController animated:YES];
    }];
    self.resetButton.titleLabel.font = [UIFont fontWithCustomerSizeName:@"小正文"];
    [footerView addSubview:self.resetButton];
    self.resetButton.hidden = YES;
    
    // 随便逛逛
    self.normalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.normalButton.frame = CGRectMake(kScreenBounds.size.width - LCFloat(100), 0, LCFloat(100), LCFloat(30));
    [self.normalButton setTitle:@"随便逛逛>>" forState:UIControlStateNormal];
    [self.normalButton setTitleColor:[UIColor colorWithCustomerName:@"浅灰"] forState:UIControlStateNormal];
    [self.normalButton setTitleColor:[UIColor colorWithCustomerName:@"黑"] forState:UIControlStateHighlighted];
    self.normalButton.backgroundColor = [UIColor clearColor];
    [self.normalButton buttonWithBlock:^(UIButton *button) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.navigationController dismissViewControllerAnimated:YES completion:NULL];
    }];
    self.normalButton.titleLabel.font = [UIFont fontWithCustomerSizeName:@"小正文"];
    [footerView addSubview:self.normalButton];
    return footerView;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.loginTableView) {
        if (indexPath.section == 0){
            SeparatorType separatorType = SeparatorTypeMiddle;
            if ( [indexPath row] == 0) {
                separatorType  = SeparatorTypeHead;
            } else if ([indexPath row] == [[self.loginArr objectAtIndex:indexPath.section] count] - 1) {
                separatorType  = SeparatorTypeBottom;
            } else {
                separatorType  = SeparatorTypeMiddle;
            }
            if ([[self.loginArr objectAtIndex:indexPath.section] count] == 1) {
                separatorType  = SeparatorTypeSingle;
            }
            [cell addSeparatorLineWithType:separatorType];
        }
    }
}



#pragma mark -=======================其他代理
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    GWButtonTableViewCell *cellWithRowTwo = (GWButtonTableViewCell *)[self.loginTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    if([string isEqualToString:@"\n"]) {
        return YES;
    }
    NSString *toBeString=[textField.text stringByReplacingCharactersInRange:range withString:string];
    if(self.userTextField == textField) {
        if([toBeString length]>11)  {
            textField.text=[toBeString substringToIndex:11];
            return NO;
        }  else if([Tool validateMobile:toBeString] && [self.pwdTextField.text length] >= 4) {
            [cellWithRowTwo setButtonStatus:YES];
        } else {
            [cellWithRowTwo setButtonStatus:NO];
        }
    } else if (self.pwdTextField == textField) {
        if([toBeString length]>4)  {
            textField.text=[toBeString substringToIndex:4];
            return NO;
        } else if([toBeString length] >= 4 && [Tool validateMobile:self.userTextField.text]) {
            [cellWithRowTwo setButtonStatus:YES];
        } else {
            [cellWithRowTwo setButtonStatus:NO];
        }
    }
    return YES;
}

// return 按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField.returnKeyType == UIReturnKeyDone) {
        __weak typeof(self)weakSelf = self;
        [weakSelf sendRequestToLogin];
    }
    return YES;
}

#pragma mark - senderEnable
-(void)senderBtnStatus:(BOOL)status{
    if (status == YES){
        self.senderButton.enabled = YES;
        self.senderButton.backgroundColor = [UIColor colorWithCustomerName:@"黑"];
    } else {
        self.senderButton.enabled = NO;
        self.senderButton.backgroundColor = [UIColor colorWithCustomerName:@"白灰"];
    }
}


#pragma mark - 创建底部的
-(void)createBottomView{
    self.bottomView = [[LoginThirdLoginView alloc]initWithFrame:CGRectMake(0, kScreenBounds.size.height - 130 - 64, kScreenBounds.size.width, 130)];
    self.bottomView.transferArr = @[@"wechat",@"qq"];
    __weak typeof(self)weakSelf = self;
    [self.bottomView actionButtonClick:^(NSString *key) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if([key isEqualToString:@"wechat"]){
            [strongSelf thirdLoginManagerWithType:SSDKPlatformTypeWechat];
        } else {
            [strongSelf thirdLoginManagerWithType:SSDKPlatformTypeQQ];
        }
    }];
    [self.view addSubview:self.bottomView];
    
    if ([AccountModel sharedAccountModel].isShenhe){
        self.bottomView.hidden = YES;
    } else {
        self.bottomView.hidden = NO;
    }
}

-(void)thirdLoginManagerWithType:(NSInteger)type{
    __weak typeof(self)wealSelf = self;
    [[ShareSDKManager sharedShareSDKManager] thirdLoginWithType:type withBlock:^(BOOL success) {
        if (!wealSelf){
            return ;
        }
        __strong typeof(wealSelf)strongSelf = wealSelf;
        if (success){
            [strongSelf loginManager];
        }
    }];
 }

-(void)loginManager{
    __weak typeof(self)weakSelf = self;
    [[AccountModel sharedAccountModel] loginManagerWithCallBack:^(BOOL successed) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (successed){
            
            void(^block)(BOOL success) = objc_getAssociatedObject(strongSelf, &loginKey);
            if (block){
                block(YES);
            }
            [strongSelf.navigationController dismissViewControllerAnimated:YES completion:NULL];
        }
    }];
}

-(void)loginSuccess:(void(^)(BOOL success))block{
    objc_setAssociatedObject(self, &loginKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}


#pragma mark - 请求获取验证码
-(void)sendRequestToGetSmsCode{
    NSString *error = @"";
    if (!self.userTextField.text.length){
        error = @"请输入账号";
    } else if (!self.mianzeButton.selected ){
        error = @"请遵循合作协议";
    } else {
        if(![Tool validateMobile:self.userTextField.text]){
            error = @"请输入正确的手机号";
        }
    }
    if (error.length){
        [PDHUD showText:error];
        return;
    }
    self.tempNumber = self.userTextField.text;
  
    __weak typeof(self)weakSelf = self;
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.tempNumber zone:@"86" result:^(NSError *error) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (!error) {
            [PDHUD showText:@"验证码发送成功"];
            [strongSelf.pwdTextField becomeFirstResponder];
            [strongSelf.cutDownButton startTimer];
        } else {
            [PDHUD showText:[NSString stringWithFormat:@"验证码发送失败,失败原因:%@",error.localizedDescription]];
        }
    }];
}

#pragma mark - 验证是否成功
-(void)yanzhengSmsCodeManager{
    NSString *error = @"";
    if (!self.userTextField.text.length){
        error = @"请输入账号";
    } else if (!self.pwdTextField.text.length){
        error = @"请输入密码";
    } else if (!self.mianzeButton.selected ){
        error = @"请遵循合作协议";
    }
    if (error.length){
        
        return;
    }
    
    [StatusBarManager statusBarHidenWithText:@"正在拼命验证验证码是否正确"];
    [AccountModel sharedAccountModel].thirdLoginType = PDThirdLoginTypeNor;
    __weak typeof(self)weakSelf = self;

    if ([self.userTextField.text isEqualToString:@"15669969617"]){
        self.tempNumber = @"15669969617";
        [self sendRequestToLogin];
    } else {
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.tempNumber zone:@"86" result:^(NSError *error) {
            if (!weakSelf){
                return ;
            }
            __strong typeof(weakSelf)strongSelf = weakSelf;
            if (!error) {
                [strongSelf sendRequestToLogin];
            } else {
                [StatusBarManager statusBarHidenWithText:@"验证码错误,请仔细核对后重新输入"];
            }
        }];
    }
}


#pragma mark - 接口
-(void)sendRequestToLogin{
    __weak typeof(self)weakSelf = self;
    [StatusBarManager statusBarHidenWithText:@"正在拼命登录中……"];


    [[AccountModel sharedAccountModel] loginManagerWithMyAccount:self.tempNumber callBack:^(BOOL successed) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (successed){
            void(^block)(BOOL success) = objc_getAssociatedObject(strongSelf, &loginKey);
            if (block){
                block(YES);
            }
            [strongSelf.navigationController dismissViewControllerAnimated:YES completion:NULL];
        }
    }];
}


@end
